/*
 * @Descripttion: 
 * @version: 
 * @Author: hzj-1510017964@qq.com
 * @Date: 2020-04-28 09:49:39
 * @LastEditors: hzj-1510017964@qq.com
 * @LastEditTime: 2020-05-07 10:18:01
 */


const utils = require('../utils')
const redisDb = require('../config/redisConfig')
const app = require('../config/appConfig')
const UserLoginDao = require('../dao/UserLoginDao')
const httpResult = require('../utils/httpResult')
var moment = require('moment');




UserLogin = async (ctx) => {
    console.log(ctx.request.body)
    let postData = ctx.request.body
    let _queryUuid = await UserLoginDao.queryUuid({ uuid: postData.uuid })

    if (_queryUuid) {
        let paylod = {
            uuid: _queryUuid.uuid,
            id: _queryUuid.id
        }
        let token = utils.createToken(paylod)

        await redisDb.set(app.TOKEN.TOKEN_IN_REDIS_DBNAME, app.REDIS.APP_REDIS_NAME + paylod.uuid, token).then(res => {
            if (res) {
                ctx.body = httpResult.success(null, null, token)
            }
        }).catch(err => {
            ctx.body = httpResult.fail(null, null, err)
        })

    } else {
        let setUuid = await UserLoginDao.setUuid({ uuid: postData.uuid })
        console.log(JSON.stringify(setUuid))
        if (setUuid) {
            let paylod = {
                uuid: setUuid.uuid,
                id: setUuid.id
            }
            let token = utils.createToken(paylod)
            console.log(token, 456789)
            await redisDb.set(app.TOKEN.TOKEN_IN_REDIS_DBNAME, app.REDIS.APP_REDIS_NAME + paylod.uuid, token).then(res => {
                if (res) {
                    ctx.body = httpResult.success(null, null, token)
                }
            }).catch(err => {
                ctx.body = httpResult.fail(null, null, err)
            })
        }
    }
}



GetOutAndInType = async (ctx) => {
    let getData = ctx.params
    let list = await UserLoginDao.getOutAndInTypeDao({ type: getData.type })
    if (list) {
        ctx.body = httpResult.success(null, null, list)
    }
}


AddUserRecord = async (ctx) => {
    let userInfor = ctx.token_state
    let postData = ctx.request.body
    if (userInfor) {
        postData.userId = userInfor.id,
            postData.state = 1
        postData.addTime = moment(new Date()).format('YYYY-MM-DD')
        let timeArr = postData.clock.split("-")
        postData.yearAndMonth = `${timeArr[0]}-${timeArr[1]}`
        let setUserRecord = await UserLoginDao.addUserRecordDao(postData)
        if (setUserRecord) {
            ctx.body = httpResult.success(null, null, true)
        }
    } else {
        ctx.body = httpResult.fail(null, null, '登录过期，token已失效')
    }
}

getUserRecordDao = async (ctx) => {


  console.log(JSON.stringify(ctx))


    let postData = ctx.request.body
    let yearAndMonth = postData.yearAndMonth
    let userInfo = ctx.token_state
    if (!userInfo) {
        ctx.body = httpResult.fail(null, null, '登录过期，token已失效')
        return
    }
    let getUserRecordDao = await UserLoginDao.getUserRecordDao({ userId: userInfo.id, yearAndMonth: yearAndMonth })
    let dataArr = []
    getUserRecordDao.forEach(v => {
        var obj = {
            time: v.clock,
            item: [],
            in: 0,
            out: 0
        }
        dataArr.push(obj)
    })
    var map = {}
    dataArr.forEach(item => map[JSON.stringify(item)] = item);
    let newArr = Object.keys(map).map(key => map[key])
    getUserRecordDao.forEach(v => {
        newArr.forEach(v2 => {
            if (v2.time == v.clock) {
                v2.item.push(v)
                v2.item.reverse()
                if (v.outAndIn) {
                    v2.in += v.money
                } else {
                    v2.out += v.money
                }
            }
        })
    })

    newArr.sort(function (a, b) {
        return Date.parse(b.time.replace(/-/g, "/")) - Date.parse(a.time.replace(/-/g, "/"));
    })

    let outNum = 0

    newArr.map(v=>{
        outNum+=v.out
    })

    let getData = {
        list:newArr,
        outNum:outNum
    }

    ctx.body = httpResult.success(null, null, getData)
}


total = async (ctx) => {
    console.log(ctx.request.body)
    let postData = ctx.request.body
    let yearAndMonth = postData.yearAndMonth

    let userInfo = ctx.token_state
    if (!userInfo) {
        ctx.body = httpResult.fail(null, null, '登录过期，token已失效')
        return
    }
    let queryData = await UserLoginDao.totalDao({ yearAndMonth: yearAndMonth, userId: userInfo.id, outAndIn: postData.outAndIn })
    console.log(queryData, 122)
    if (queryData) {
        ctx.body = httpResult.success(null, null, queryData)
    }
}



setQuota = async (ctx) => {
    let postData = ctx.request.body
    let userInfo = ctx.token_state
    if (!userInfo) {
        ctx.body = httpResult.fail(null, null, '登录过期，token已失效')
        return
    }
    let queryData = await UserLoginDao.setQuotaDao({ quota: postData.quota }, { id: userInfo.id })
    if (queryData) {
        ctx.body = httpResult.success(null, null, queryData)
    }
}

getUserInfo = async (ctx) => {
    let userInfo = ctx.token_state
    if (!userInfo) {
        ctx.body = httpResult.fail(null, null, '登录过期，token已失效')
        return
    }
    let queryData = await UserLoginDao.getUserInfo({ id: userInfo.id })
    if (queryData) {
        ctx.body = httpResult.success(null, null, queryData)
    }
}




module.exports = {
    UserLogin,
    GetOutAndInType,
    AddUserRecord,
    getUserRecordDao,
    total,
    setQuota,
    getUserInfo
}



